package com.parking.status.sync.netty.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.parking.status.sync.netty.entity.MessageType;
import com.parking.status.sync.netty.entity.ResponseError;
import com.parking.status.sync.netty.entity.ResponsePre;
import com.parking.status.sync.netty.event.ResponseReceivedEvent;
import com.parking.status.sync.netty.event.ResponseReceivedEventParameters;
import com.parking.status.sync.netty.service.EventPublishService;
import com.parking.status.sync.netty.util.PojoMapper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by Administrator on 2015/9/18.
 */
@ChannelHandler.Sharable
public class ResponseBodyDecoder extends MessageToMessageDecoder<String> {

    @Autowired
    private EventPublishService service;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, String messageBody, List<Object> out) throws Exception {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(messageBody);
        JsonNode codeNode = rootNode.get(MessageType.FIELD_NAME_CODE);
        String msgType = codeNode.toString();

        ResponsePre request = null;
        Class<? extends ResponsePre> classtype = MessageType.getMessageClass(msgType);
        if (classtype != null) {
            request = PojoMapper.fromJson(messageBody, classtype);
        } else {
//            //TODO
//            ResponseError error = new ResponseError();
//            ResponseReceivedEvent event = new ResponseReceivedEvent(
//                    new ResponseReceivedEventParameters(channelHandlerContext, error));
//            service.publishEvent(event);
            return;
        }

        if(request != null) {
            out.add(request);
        } else {
            //TODO do nothing?

        }

    }
}